<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryObj.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="hChange"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          show-checkbox
          :data="depList"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          check-strictly
          @current-change="hcurrentChange"
        />
        <!-- current-change当前选中节点变化时触发的事件 -->
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <!-- 权限按钮 -->
          <!-- 第一种写法:<el-button v-if="$store.state.user.userInfo.roles.points.includes('test')" size="mini" @click="hExport">excel导出</el-button> -->
          <!-- 第二种 自定义指令 -->
          <el-button v-allow="'excel'" size="mini" @click="hExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->

        <el-table :data="employList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <!-- 头像 -->
            <template v-slot="{row}">
              <img v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" class="user-avatar">
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>

          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">

            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>

          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <!-- 动态路由传参 -->
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="role(row.id)">角色</el-button>
              <!-- 气泡框 -->
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          :current-page="queryObj.page"
          :page-sizes="[5,10,15]"
          layout="prev, pager, next,sizes"
          :background="true"
          :page-size="queryObj.pagesize"
          :total="total"
          @current-change="changePage"
        />
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" />
    <!-- 角色 -->
    <assign-role ref="assignRole" :show-dialog-role.sync="showDialogRole" :cur-id="curId" />
  </div>
</template>

<script>

import { arr2tree } from '@/utils'
import { getDepartment } from '@/api/department'
import { getEmployeeList, exportEmployee, delEmployee } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
import AssignRole from './components/assignRole.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel,
    AssignRole
  },
  data() {
    return {
      curId: -1,
      showExcelDialog: false,
      showDialogRole: false,
      depList: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryObj: {
        page: 1,
        pagesize: 10,
        keyword: null,
        departmentId: null
      },
      employList: [],
      total: 0,
      page: 1,
      pagesize: 10
    }
  },
  created() {
    this.getDepartment()// 部门列表
  },
  methods: {
    // 获取-部门列表
    async getDepartment() {
      const res = await getDepartment()
      // console.log(res.data)
      const rs = arr2tree(res.data, 0)
      this.depList = rs
      // console.log(this.$refs.tree, rs[0])

      // 第一个节点
      const id = rs[0].id
      // console.log(id)
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys([id])
        this.$refs.tree.setCurrentKey(id)
      })
      // 发一次请求 获取员工列表
      this.loadEmployment()
    },
    // 当前选中节点变化时触发的事件
    hcurrentChange(data, node) {
      // console.log(data, node)
      // 记录id
      this.queryObj.departmentId = data.id
      // 切换部门时，查询第一页数据
      this.queryObj.page = 1 // 设置第一页
      // 发请求拿到对应的部门信息
      this.loadEmployment()
    },
    // 发请求获取员工列表
    async loadEmployment() {
      // console.log('查询条件是', this.queryObj)
      const res = await getEmployeeList(this.queryObj)
      // axios在发请求的时候,如果你的参数值为null,它会丢弃这个参数
      // console.log(res)
      this.employList = res.data.rows
      this.total = res.data.total
    },
    // 切换页码
    changePage(newPage) {
      this.queryObj.page = newPage // 赋值新页码
      this.loadEmployment() // 查询数据
    },
    // 根据名字模糊查询
    // 输入框中的内容变化的时候,发请求  --防抖(高频触发只执行一次)
    hChange() {
      // console.log(this.queryObj.keyword)

      clearTimeout(this.timerId)
      // 更新参数 v-model
      this.timerId = setTimeout(() => {
        // 发请求 从第一页开始找
        this.queryObj.page = 1
        this.loadEmployment()
      }, 1000)
    },

    // 导出
    async hExport() {
      // 1.调用接口
      const res = await exportEmployee()// 导出所有的员工接口
      // 2.改下接口
      // 使用一个npm包 直接将blob文件下载到本地 file-saver
      console.log(res)
      // FileSaver.saveAs(blob对象,文件名称)
      // 3.保存文件
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    // 删除
    async confirmDel(id) {
      // 调删除请求
      console.log(id)
      await delEmployee(id)
      // 如果是当前页的最后一条数据,要向前翻一页
      if (this.depList.length === 1) {
        if (this.page > 1) { this.page-- }
      }
      this.loadEmployment()
      this.$message.success('删除员工成功')
    },
    // 点击角色
    async role(id) {
      console.log(id)
      this.curId = id
      this.showDialogRole = true

      this.$nextTick(() => {
        this.$refs.assignRole.getRoles()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
          margin-right: 5px;
        }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
